<template>
  <div class="history-data-management">
    <!-- 顶部区域 -->
    <div class="top-section">
      <div class="header-compact">
        <h1>历史数据管理</h1>
      </div>
      <div class="stats-section">
        <div class="stat-card success">
          <div class="stat-value">{{ stats.find(s => s.key === 'total')?.value || '0' }}</div>
          <div class="stat-label">总记录数</div>
        </div>
        <div class="stat-card info">
          <div class="stat-value">{{ stats.find(s => s.key === 'today')?.value || '0' }}</div>
          <div class="stat-label">今日记录</div>
        </div>
        <div class="stat-card warning">
          <div class="stat-value">{{ stats.find(s => s.key === 'size')?.value || '0.00' }}</div>
          <div class="stat-label">数据库大小(MB)</div>
        </div>
        <div class="stat-card primary">
          <div class="stat-value">{{ formatLastUpdate(stats.find(s => s.key === 'lastUpdate')?.value) }}</div>
          <div class="stat-label">最新记录时间</div>
        </div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :model="searchForm" class="search-form" @submit.prevent="handleSearch">
          <el-form-item label="单据号">
            <el-input v-model="searchForm.documentNumber" clearable placeholder="请输入单据号"/>
          </el-form-item>
          <el-form-item label="推送时间">
            <el-date-picker
                v-model="searchForm.dateRange"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                range-separator="至"
                start-placeholder="开始时间"
                type="datetimerange"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

          <el-form-item>
            <el-button :loading="loading" type="primary" @click="handleSearch">
              <el-icon size="16">
                <Search/>
              </el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon size="16">
                <Refresh/>
              </el-icon>
              重置
            </el-button>
            <el-button :loading="loading" type="success" @click="loadData">
              <el-icon size="16">
                <Search/>
              </el-icon>
              查询数据
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据展示区域 -->
      <div class="data-section">
        <div class="data-header">
          <div class="data-header-left">
            <h3>历史数据列表</h3>
            <div class="select-all-container">
              <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
            </div>
          </div>
          <div class="data-controls">
            <div class="tab-buttons">
              <el-button
                  :type="activeTab === 'summary' ? 'primary' : ''"
                  @click="switchTab('summary')"
              >
                概括结果
              </el-button>
              <el-button
                  :type="activeTab === 'detailed' ? 'primary' : ''"
                  @click="switchTab('detailed')"
              >
                详细错误
              </el-button>
            </div>
            <el-button
                v-show="selectedItems.length > 0"
                :loading="deleteLoading"
                type="danger"
                @click="handleBatchDelete"
            >
              <el-icon size="16">
                <Delete/>
              </el-icon>
              批量删除
            </el-button>
          </div>
        </div>

        <div v-loading="loading" class="data-container">
          <div v-if="dataList.length === 0" class="empty-state">
            <el-empty description="暂无数据"/>
          </div>
          <div v-else>
            <DocumentItem
                v-for="item in dataList"
                :key="`${item.单据号}_${item.推送时间}`"
                :active-tab="activeTab"
                :item="item"
                :selected="selectedItems.includes(`${item.单据号}_${item.推送时间}`)"
                @delete="handleItemDelete"
                @select="handleItemSelect"
            />
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="total > 0" class="pagination-container">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {computed, onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Delete, Refresh, Search} from '@element-plus/icons-vue'
import DocumentItem from './DocumentItem.vue'
import {historyDataApi} from '../api/historyData.js'

export default {
  name: 'HistoryDataManagement',
  components: {
    DocumentItem,
    Search,
    Refresh,
    Delete
  },
  setup() {
    // 响应式数据
    const loading = ref(false)
    const deleteLoading = ref(false)
    const activeTab = ref('summary')
    const selectAll = ref(false)
    const selectedItems = ref([])
    const currentPage = ref(1)
    const pageSize = ref(20)
    const total = ref(0)
    const dataList = ref([])

    const stats = ref([
      {key: 'total', label: '总记录数', value: '0'},
      {key: 'today', label: '今日记录', value: '0'},
      {key: 'size', label: '数据库大小(MB)', value: '0.00'},
      {key: 'lastUpdate', label: '最新记录时间', value: '-'}
    ])

    const searchForm = reactive({
      documentNumber: '',
      dateRange: null
    })

    // 计算属性
    const searchParams = computed(() => {
      const params = {
        page: currentPage.value,
        limit: pageSize.value
      }

      if (searchForm.documentNumber) {
        params.document_number = searchForm.documentNumber
      }

      if (searchForm.dateRange && searchForm.dateRange.length === 2) {
        params.start_time = searchForm.dateRange[0]
        params.end_time = searchForm.dateRange[1]
      }

      return params
    })

    // 方法
    const loadStats = async () => {
      try {
        const response = await historyDataApi.getStats()
        if (response.success) {
          stats.value[0].value = response.data.total_records.toString()
          stats.value[1].value = response.data.today_records.toString()
          stats.value[2].value = response.data.db_size_mb.toFixed(2)
          stats.value[3].value = response.data.latest_record_time || '-'
        }
      } catch (error) {
        console.error('加载统计信息失败:', error)
      }
    }

    const loadData = async () => {
      loading.value = true
      try {
        const response = await historyDataApi.getData(searchParams.value)
        if (response.success) {
          dataList.value = response.data || []
          total.value = response.total || 0
        } else {
          ElMessage.error(response.message || '加载数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
      loadData()
    }

    const resetSearch = () => {
      searchForm.documentNumber = ''
      searchForm.dateRange = null
      currentPage.value = 1
      loadData()
    }

    const switchTab = (tab) => {
      activeTab.value = tab
    }

    const handleSelectAll = (checked) => {
      if (checked) {
        selectedItems.value = dataList.value.map(item => `${item.单据号}_${item.推送时间}`)
      } else {
        selectedItems.value = []
      }
    }

    const handleItemSelect = (itemKey, selected) => {
      if (selected) {
        if (!selectedItems.value.includes(itemKey)) {
          selectedItems.value.push(itemKey)
        }
      } else {
        const index = selectedItems.value.indexOf(itemKey)
        if (index > -1) {
          selectedItems.value.splice(index, 1)
        }
      }

      // 更新全选状态
      selectAll.value = selectedItems.value.length === dataList.value.length
    }

    const handleItemDelete = async (item) => {
      try {
        await ElMessageBox.confirm('确定要删除这条记录吗？', '确认删除', {
          type: 'warning'
        })

        const response = await historyDataApi.deleteItem(item.单据号, item.推送时间)
        if (response.success) {
          ElMessage.success('删除成功')
          loadData()
          loadStats()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    const handleBatchDelete = async () => {
      if (selectedItems.value.length === 0) {
        ElMessage.warning('请选择要删除的项目')
        return
      }

      try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedItems.value.length} 个项目吗？`,
            '确认批量删除',
            {type: 'warning'}
        )

        deleteLoading.value = true
        const deletePromises = selectedItems.value.map(itemKey => {
          const [documentNumber, pushTime] = itemKey.split('_')
          return historyDataApi.deleteItem(documentNumber, pushTime)
        })

        await Promise.all(deletePromises)
        ElMessage.success(`成功删除 ${selectedItems.value.length} 个项目`)
        selectedItems.value = []
        selectAll.value = false
        loadData()
        loadStats()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        }
      } finally {
        deleteLoading.value = false
      }
    }

    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
      loadData()
    }

    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadData()
    }

    const formatLastUpdate = (timeStr) => {
      if (!timeStr || timeStr === '-') return '-'
      try {
        const date = new Date(timeStr)
        const now = new Date()
        const diff = now - date
        const minutes = Math.floor(diff / 60000)

        if (minutes < 1) return '刚刚'
        if (minutes < 60) return `${minutes}分钟前`
        if (minutes < 1440) return `${Math.floor(minutes / 60)}小时前`
        return date.toLocaleDateString('zh-CN')
      } catch {
        return timeStr
      }
    }

    // 生命周期
    onMounted(() => {
      loadStats()
      // 移除自动加载数据的逻辑，改为手动查询
      // loadData()
    })

    return {
      loading,
      deleteLoading,
      activeTab,
      selectAll,
      selectedItems,
      currentPage,
      pageSize,
      total,
      dataList,
      stats,
      searchForm,
      loadStats,
      loadData,
      handleSearch,
      resetSearch,
      switchTab,
      handleSelectAll,
      handleItemSelect,
      handleItemDelete,
      handleBatchDelete,
      handleSizeChange,
      handleCurrentChange,
      formatLastUpdate
    }
  }
}
</script>

<style scoped>
.history-data-management {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.top-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 30px;
  margin-bottom: 20px;
  border-radius: 15px 15px 0 0;
}

.header-compact {
  flex: 1;
}

.header-compact h1 {
  font-size: 1.8em;
  margin: 0 0 5px 0;
  font-weight: 300;
}

.header-compact p {
  font-size: 0.9em;
  opacity: 0.9;
  margin: 0;
}

.stats-section {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.stat-card {
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(10px);
  color: white;
  padding: 20px;
  border-radius: 12px;
  text-align: center;
  min-width: 140px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.stat-card.success::before {
  background: linear-gradient(90deg, #56ab2f 0%, #a8e6cf 100%);
}

.stat-card.warning::before {
  background: linear-gradient(90deg, #f093fb 0%, #f5576c 100%);
}

.stat-card.info::before {
  background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
}

.stat-card.primary::before {
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
}

.stat-card:hover {
  transform: translateY(-3px);
  background: rgba(255, 255, 255, 0.25);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.stat-card:hover::before {
  opacity: 1;
}

.stat-value {
  font-size: 2em;
  margin: 0 0 8px 0;
  font-weight: 700;
  line-height: 1;
}

.stat-label {
  font-size: 0.9em;
  margin: 0;
  opacity: 0.9;
  font-weight: 500;
}

.main-content {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  padding: 40px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.2);
  margin: 20px;
  animation: fadeIn 0.6s ease-out;
}

.search-section {
  margin-bottom: 40px;
  background: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 30px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 24px;
  align-items: end;
}

.data-section {
  margin-bottom: 40px;
}

.data-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px 0;
  border-bottom: 2px solid rgba(102, 126, 234, 0.1);
  position: relative;
}

.data-header::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 60px;
  height: 2px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 1px;
}

.data-header-left {
  display: flex;
  align-items: center;
  gap: 24px;
}

.data-header h3 {
  color: #2d3748;
  font-size: 1.5em;
  font-weight: 700;
  margin: 0;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.select-all-container {
  display: flex;
  align-items: center;
  gap: 10px;
  background: rgba(255, 255, 255, 0.7);
  padding: 8px 16px;
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.select-all-container:hover {
  background: rgba(255, 255, 255, 0.9);
  transform: translateY(-1px);
}

.data-controls {
  display: flex;
  gap: 20px;
  align-items: center;
}

.tab-buttons {
  display: flex;
  gap: 4px;
  background: rgba(255, 255, 255, 0.7);
  padding: 6px;
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.data-container {
  min-height: 300px;
  background: rgba(255, 255, 255, 0.4);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 20px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #718096;
}

.empty-state .empty-icon {
  font-size: 4rem;
  margin-bottom: 20px;
  opacity: 0.6;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.empty-state h3 {
  font-size: 1.3rem;
  margin-bottom: 12px;
  color: #4a5568;
  font-weight: 600;
}

.empty-state p {
  font-size: 1rem;
  opacity: 0.8;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  padding: 20px;
}

/* 按钮样式 */
.el-button {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.el-button .el-icon {
  transition: all 0.3s ease;
}

.el-button:hover .el-icon {
  transform: scale(1.1);
}

.el-button--primary:hover .el-icon {
  filter: drop-shadow(0 2px 4px rgba(64, 158, 255, 0.4));
}

.el-button--danger:hover .el-icon {
  filter: drop-shadow(0 2px 4px rgba(245, 108, 108, 0.4));
}

@media (max-width: 768px) {
  .top-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }

  .stats-section {
    width: 100%;
    justify-content: space-between;
  }

  .stat-card {
    flex: 1;
    min-width: 80px;
  }

  .search-form {
    grid-template-columns: 1fr;
  }

  .data-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .data-controls {
    width: 100%;
    justify-content: space-between;
  }
}
</style>